#include "02_FrameBuffer.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <linux/input.h>

int Pos_x = 0;
int Pos_y = 0;

int main(int argc, const char *argv[])
{
	int fd = 0;
	struct input_event env;
	signed char data[3];
	int bytes = 0;
	int left, middle, right;
	signed char x, y;
	FB_T *pFb;
	unsigned char TmpBuff[800][1024] = {0};
	
	pFb = FrameBuffInit("/dev/fb0");

	fd = open("/dev/input/mice", O_RDWR);
	if (-1 == fd)
	{
		perror("fail to open");
		return -1;
	}
	
	ClearScreen(pFb);
	SaveMouseInfo(pFb, Pos_x, Pos_y, 15, 15, TmpBuff, 800);
	DrawBmp(pFb, Pos_x, Pos_y, 15, 15, "mouse.bmp");

	while (1)
	{
		bytes = read(fd, data, sizeof(data));
		if (bytes > 0)
		{
			left = data[0] & 0x1;
			right = data[0] & 0x2;
			middle = data[0] & 0x4;
			
			x = data[1];
			y = data[2];
			ReloadMouseInfo(pFb, Pos_x, Pos_y, 15, 15, TmpBuff, 800);
			if (Pos_x + x >= 0 && Pos_x + x <= pFb->ScreenInfo.xres_virtual - 15)
			{
				Pos_x += x;
			}
			if (Pos_y - y >= 0 && Pos_y - y <= pFb->ScreenInfo.yres_virtual - 15)
			{
				Pos_y -= y;
			}
			SaveMouseInfo(pFb, Pos_x, Pos_y, 15, 15, TmpBuff, 800);
			DrawBmp(pFb, Pos_x, Pos_y,  15, 15, "mouse.bmp");
			if (left)
			{
				printf("left button press! (%d, %d)\n", Pos_x, Pos_y);
			}
			if (right)
			{
				printf("right button press! (%d, %d)\n", Pos_x, Pos_y);
			}
		}
	}

	close(fd);

	return 0;
}
